package com.aodao.sms.urlconn;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Random;
/**
 * 使用说明：
 * 1、需要修改对应的package路径
 * 2、添加fastjson依赖，也可以适当的修改为自己适用的json包依赖
     <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.1.33.android</version>
     </dependency>
 * 3、android调用建议使用子线程，避免使用ui线程，防止应用崩溃
 */

/**
 * @author dzp
 * @Description:
 * @date 2017年06月29日 10:16
 */
public class SmsClient {

    private final String appId = ${appId};
    private final String appKey = ${appKey};
    private final String errCodeStr = ${errCodeStr};
    private final String apiUrl = "https://sms.aodao.com.cn/api/api.php";
    
    private JSONObject errCodeJson;

    public JSONObject sendMsg(JSONObject param) {
        try {
            if (param == null || param.size() == 0) {
                return error("缺少参数");
            } else {
                String token = randomStr();
                Long now = System.currentTimeMillis();

                JSONObject smsJson = new JSONObject();

                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                if (null != param.getString("name") && !"".equals(param.getString("name"))) {
                    smsJson.put("name", param.getString("name") + "_" + format.format(now) + "_" + token);
                } else {
                    smsJson.put("name", format.format(now) + "_" + token);
                }
                if (null != param.getString("sendtime") && !"".equals(param.getString("sendtime"))) {
                    smsJson.put("sendtime", param.getString("sendtime"));
                } else {
                    smsJson.put("sendtime", now / 1000 + "");
                }

                smsJson.put("appid", appId);
                smsJson.put("appkey", appKey);
                smsJson.put("mobile", param.getString("mobile"));
                smsJson.put("time", now / 1000 + "");
                smsJson.put("token", token);
                smsJson.put("sign", SHA1(MD5(token + now / 1000 + appKey + appId)));
                smsJson.put("inform_type", param.getString("inform_type"));
                smsJson.put("template_type", param.getString("template_type"));
                smsJson.put("typeid", param.getString("typeid"));
                smsJson.put("content_variable", param.get("content_variable"));
                String postData = "a=sendsms&agv=" + smsJson.toJSONString();

                System.out.println("apiUrl=" + apiUrl + ",postData=" + postData);
                String result = post(apiUrl, postData);
                JSONObject resultJson = JSONObject.parseObject(result);
                System.out.println("result:" + resultJson.toJSONString());
                return resultJson;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 实名验证及增量报告查询接口
     * @param param
     * @return
     */
    public JSONObject check(JSONObject param) {
        try {
            if (param == null || param.size() == 0) {
                return error("缺少参数");
            } else {
                String token = randomStr();
                Long now = System.currentTimeMillis();
                JSONObject smsJson = new JSONObject();

                smsJson.put("appid", appId);
                smsJson.put("appkey", appKey);
                smsJson.put("time", now / 1000 + "");
                smsJson.put("token", token);
                smsJson.put("sign", SHA1(MD5(token + now / 1000 + appKey + appId)));
                smsJson.put("cklist", param.getString("cklist"));//业务查询标志,cklist=4（实名认证查询接口），cklist=5（人脸识别实名认证查询接口）
                smsJson.put("typeid", param.getString("typeid"));//根据业务类型ID查询该业务类型下有效使用量
                smsJson.put("mobile", param.getString("mobile"));//被查询者手机号
                smsJson.put("username", param.getString("username"));//被查询者姓名
                smsJson.put("idcard", param.getString("idcard"));//被查询者身份证号
                String postData = "a=sendreport&agv=" + smsJson.toJSONString();
                System.out.println(postData);
                String result = post(apiUrl, postData);
                JSONObject resultJson = JSONObject.parseObject(result);
                System.out.println("result:" + resultJson.toJSONString());
                return resultJson;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String randomStr() {
        return String.valueOf(Math.abs(new Random(System.currentTimeMillis()).nextLong()));
    }

    /**
     * 错误返回json
     *
     * @param errMsg
     * @return
     */
    private JSONObject error(String errMsg) {
        JSONObject error = new JSONObject();
        error.put("errno", -1);
        error.put("message", errMsg);
        return error;
    }

    /**
     * md5
     *
     * @param input
     * @return
     */
    private static String MD5(String input) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(input.getBytes());
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < md.length; i++) {
                String shaHex = Integer.toHexString(md[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * sha1
     *
     * @param decript
     * @return
     */
    private static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 根据错误码获取错误信息
     *
     * @param code
     * @return
     */
    public String getMsgByCode(String code) {
        if (errCodeStr != null && !"".equals(errCodeStr) && errCodeJson == null) {
            errCodeJson = JSONObject.parseObject(errCodeStr);
            if (errCodeJson == null || errCodeJson.size() == 0) {
                return null;
            }
        }
        return errCodeJson.getString(code);
    }

    /**
     * httpUrlConnection,post提交
     *
     * @param urlStr
     * @param params
     * @return
     * @throws IOException
     */
    private String post(String urlStr, String params) throws IOException {
        String response = "";
        OutputStreamWriter out = null;
        InputStream in = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);
            out.flush();
            out.close();
            int code = connection.getResponseCode();
            if (code == 200)
                in = connection.getInputStream();
            else
                in = connection.getErrorStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String readLine = null;
            while ((readLine = br.readLine()) != null)
                response = response + readLine;
            in.close();
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                in = null;
            if (out != null)
                out = null;
        }
        return response;

    }
}
